package com.ss.whisper2.controller;

import com.ss.whisper2.pojo.FileMessage;
import com.ss.whisper2.pojo.entity.user.User;
import com.ss.whisper2.service.impl.FileServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Objects;

@Controller
public class FileController {
	private static final Logger LOGGER = LoggerFactory.getLogger(FileController.class);
	@Autowired
	private FileServiceImpl fileService;

	@RequestMapping("/file-list")
	public String getCourseList(HttpSession session) {
		session.setAttribute("fileList",fileService.getFileList());
		return "file-list";
	}
	@PostMapping("/upload")
	@ResponseBody
	public FileMessage upload(@RequestParam("file") MultipartFile file, HttpSession session) {
		if (Objects.isNull(file)){
			return new FileMessage(0,"失败","上传失败");
		}
		User user=(User)session.getAttribute("user");
		//fileService.record(user.getUsername(),file.getOriginalFilename());
		//fileService.upload(file);
		return new FileMessage(1,"成功","上传成功");
	}

	@GetMapping("/download")
	@ResponseBody
	public String fileDownload(@RequestParam("fileName") String fileName, HttpServletResponse response){
		//可增加记录下载信息：用户、文件名、日期、累计下载量等
		LOGGER.info(fileName);
		if (Objects.isNull(fileName)){
			return "失败";
		}
		return fileService.download(fileName, response);
	}

}
